package com.glory.gloryquickui.base

import android.os.Bundle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.rxLifeScope
import com.glory.gloryquickui.utils.InitUtils
import com.glory.gloryquickui.utils.show
import com.glory.hiwork.mvvm.bean.CallObserveBean
import com.glory.hiwork.mvvm.bean.ToastMessageBean
import com.glory.hiwork.mvvm.utils.SingleLiveEvent
import com.rxjava.rxlife.ScopeViewModel
import kotlinx.coroutines.CoroutineScope

open class BaseViewModel : ScopeViewModel(InitUtils.instance!!), LifecycleObserver {

    val defUI: UIChange by lazy { UIChange() }

    fun launchWithError(
        block: suspend CoroutineScope.() -> Unit,
        error: () -> Unit,
        isShowDialog: Boolean = true
    ) {
        rxLifeScope.launch({
            block()
        }, {
            it.show()
            error()
        }, {
            if (isShowDialog) defUI.showDialog.call()
        }, {
            defUI.dismissDialog.call()
            defUI.complete.call()
        })
    }

    fun launchOnlyResult(
        block: suspend CoroutineScope.() -> Unit,
        isShowDialog: Boolean = true
    ) {
        rxLifeScope.launch({
            block()
        }, {
            it.show()
        }, {
            if (isShowDialog) defUI.showDialog.call()
        }, {
            defUI.dismissDialog.call()
            defUI.complete.call()
        })
    }

    fun launchWithComplete(
        block: suspend CoroutineScope.() -> Unit,
        complete: () -> Unit,
        isShowDialog: Boolean = true
    ) {
        rxLifeScope.launch({
            block()
        }, {
            it.show()
        }, {
            if (isShowDialog) defUI.showDialog.call()
        }, {
            defUI.dismissDialog.call()
            defUI.complete.call()
            complete()
        })
    }

    fun launchWithErrorAndComplete(
        block: suspend CoroutineScope.() -> Unit,
        error: () -> Unit = {},
        complete: () -> Unit = {},
        isShowDialog: Boolean = true
    ) {
        rxLifeScope.launch({
            block()
        }, {
            it.show()
            error()
        }, {
            if (isShowDialog) defUI.showDialog.call()
        }, {
            defUI.dismissDialog.call()
            defUI.complete.call()
            complete()
        })
    }


    /**
     * UI事件
     */
    inner class UIChange {
        val showDialog by lazy { SingleLiveEvent<String>() }
        val dismissDialog by lazy { SingleLiveEvent<Void>() }
        val toastEvent by lazy { SingleLiveEvent<ToastMessageBean>() }
        val complete by lazy { SingleLiveEvent<Void>() }
        val startActivity by lazy { SingleLiveEvent<Bundle>() }
        val callObserve by lazy { SingleLiveEvent<CallObserveBean>() }
    }
}